// 退款原因类型
var rdfundReasonTypeTable;
// 平台退款原因关联
var rdfundReasonRelationTable;
// 平台退款原因
var ecRefundReasonTable;

$(document).ready(function () {
    
    $.validator.addMethod("checkLetter", function(value, element) {
        var reg = /^[0-9a-zA-Z\u4E00-\u9FA5\r\n\s/.]*$/; 
        if (!reg.test(value)) {
            return false;
        }
        
        return true;
    }, "请输入数字，大小写字母，汉字");
    
    $("#newForm").validate({
        debug:true,
        errorPlacement: function(error, element)
        {
            error.insertAfter(element);
        }
    });

    $("#editForm").validate({
        debug:true,
        errorPlacement: function(error, element)
        {
            error.insertAfter(element);
        }
    });

    // 退款原因类型list
    rdfundReasonTypeTable = $('#tblRefundReason').DataTable({
        "processing": true,
        "serverSide": true,
        "lengthMenu" : [ [ 10, 25, 50, 100, 500, 1000 ], [ 10, 25, 50, 100, 500, 1000] ],
        "dom": '<"bottom"rtflp>',
        "searching": false,
        "pagingType": "full_numbers",
        "deferRender": true,
        "ajax": {
            "url": "/rdfundReasonType/getRdfundReasonTypeList.action",
            "data": function ( d ) {
                d.quickSearch = encodeURI($('#quickSearch').val());
            }
        },
        "tableTools": {
            "sRowSelect": "bootstrap"
        },
        "columns": [
            {"data": "refundReasonCode", "searchable": false},
            {"data": "refundReasonName", "searchable": false},
            {"data": "remark", "searchable": false},
            {"data": "operation", "searchable": false, "orderable": false}
        ],
        "columnDefs": [
            {"className": "truncate-text rdfundReasonType-column-detail", "targets":[0]},
            {"className": "truncate-text rdfundReasonType-column-detail", "targets":[1]},
            {"className": "truncate-text rdfundReasonType-column-detail", "targets":[2]},
            {"targets":[3]}
        ],
        "order": [[ 0, "asc" ]]
    });
    
    // 文字过长截断显示悬浮框
    $("#tblRefundReason").tooltip({
        selector: ".rdfundReasonType-column-detail",
        container: "body",
        title: function() {
            if ($(this)[0].scrollWidth > $(this).outerWidth()) {
                return $(this).text();
            }
        }
    });
    
    // 快速搜索
    $("#btnQuickSearch").click(function () {
        rdfundReasonTypeTable.draw();
    });

    // 搜索框的回车事件
    $('#quickSearch').keydown(function(e){
        if(e.keyCode==13){
            $("#btnQuickSearch").click();
        }
    }); 

    $('#frmNewRdfundReasonType').on('hidden.bs.modal', function () {
        $("#newForm")[0].reset();
    });
    
    $('#frmNewRdfundReasonType').on('hide.bs.modal', function () {
        window.top.window.returnCustomModalDialog();
        $("#newForm").validate().clear();
    });
    
    $('#frmModifyRdfundReasonType').on('hidden.bs.modal', function () {
        $("#editForm")[0].reset();
    });

    $('#frmModifyRdfundReasonType').on('hide.bs.modal', function () {
        window.top.window.returnCustomModalDialog();
        $("#editForm").validate().clear();
    })
    
    $('#frmSelPlatform').on('hide.bs.modal', function () {
        window.top.window.returnCustomModalDialog();
    });

    $('#frmEditPlatform').on('hidden.bs.modal', function () {
        $("#editPlatformForm")[0].reset();
    });
    
    $('#frmEditPlatform').on('hide.bs.modal', function () {
        window.top.window.returnCustomModalDialog();
        window.top.window.borrowCustomModalDialog($("#frmSelPlatform"));
    });
    
});

//弹出新增退款原因类型对话框
$("#newRdfundReasonTypeHref").click(function () {
    // 初始化退款原因类型控件 - 开始
    initApprOptionComp4Add();
    // 初始化退款原因类型控件 - 结束
    var editDialog = window.top.window.borrowCustomModalDialog($("#frmNewRdfundReasonType"));
    editDialog.modal({show:true, backdrop:'static'});
});

/*
 * 新增界面审核选项的控件初始化
 */
var initApprOptionComp4Add = function(){
    var $context = $("#frmNewRdfundReasonType").find("#authenOption");
    initOptionInitValue($context);
    initOptionCompEvent($context);
}

/*
 * 修改界面审核选项的控件初始化
 */
var initApprOptionComp4Modify = function(jsonData){
    var $context = $("#frmModifyRdfundReasonType").find("#authenOption");
    initOptionInitValue($context);
    initOptionCompEvent($context);
    initOptionValue4Edit($context,jsonData)
}

/*
 * 审核选项的控件取值初始化
 */
var initOptionInitValue = function($context){
    $('input[type="checkbox"],input[type="radio"]', $context).iCheck({
        checkboxClass : 'icheckbox_flat-red',
        radioClass : 'iradio_flat-red'
    });
    $("#chkForceAppr,#chkContainRefundSku,#chkRefReciptState,#chkReturnException",$context).iCheck("uncheck");
    $("#hasProcessingRecipt,#hasSendGoods,#returnUnMatch,#returnBroken",$context).iCheck("disable");
};

var initOptionValue4Edit = function($context,jsonData){
    
    if(!!jsonData){
        var options = $.parseJSON(jsonData.apprRuleString);
        if(!!options.cRS){
            if(jsonData.isForceAppr=="y"){
                $("#chkForceAppr",$context).iCheck("check");
            }

            
            if(options.cRS.enable == "y"){
                $("#chkContainRefundSku",$context).iCheck("check");
            }

            if(options.rRS.enable == "y"){
                $("#chkRefReciptState",$context).iCheck("check");
                if(options.rRS.hPR == "y"){
                    $("#hasProcessingRecipt",$context).iCheck("check");
                }else{
                    $("#hasSendGoods",$context).iCheck("check");
                }
            }

            if(options.rE.enable == "y"){
                $("#chkReturnException",$context).iCheck("check");
                $("#returnUnMatch",$context).iCheck("check");
                if(options.rE.rB == "y"){
                    $("#returnBroken",$context).iCheck("check");

                }
            }
        }

    }
}

/*
 * 审核选项的控件事件初始化:
 * 允许强制审核,默认不勾选，勾选后可对该系统原因类型的退款单执行强制审核操作，否则不可操作。
 * 审核规则：（注：主规则默认不勾选；主规则不勾选，子规则不可选）
 */
var initOptionCompEvent = function($context){
    
    $("#chkRefReciptState",$context).on("ifChecked",function(){
        $("#hasProcessingRecipt,#hasSendGoods",$context).iCheck("enable");
        $("#hasProcessingRecipt",$context).iCheck("check");
    }).on("ifUnchecked",function(){
        $("#hasProcessingRecipt,#hasSendGoods",$context).iCheck("disable");
        $("#hasProcessingRecipt,#hasSendGoods",$context).iCheck("uncheck");
    });
    
    $("#chkReturnException",$context).on("ifChecked",function(){
        $("#returnBroken",$context).iCheck("enable");
        $("#returnUnMatch",$context).iCheck("check");
    }).on("ifUnchecked",function(){
        $("#returnBroken",$context).iCheck("disable");
        $("#returnBroken",$context).iCheck("uncheck");
        $("#returnUnMatch",$context).iCheck("unCheck");
    });
}

// 保存新增退款原因类型
$("#btnSave").click(function () {
    window.top.window.returnCustomModalDialog();

    if(!$("#newForm").valid()) {
        window.top.window.borrowCustomModalDialog($("#frmNewRdfundReasonType"));
        return false;
    }

    var refundReasonCode = $('#refundReasonCode').val();
    var refundReasonName = $('#refundReasonName').val();
    var remark = $('#remark').val();
    var data = {
        "refundReasonCode": refundReasonCode,
        "refundReasonName": refundReasonName,
        "remark": remark
        // --- 审核选项设置 --- 
        ,"isForceAppr":getIsForceAppr($("#frmNewRdfundReasonType"))
        ,"apprRule":getRuleContent($("#frmNewRdfundReasonType"))
        // --- 审核选项设置 --- 
    }
    
    var newForm=window.top.window.borrowCustomModalDialog($("#frmNewRdfundReasonType"));

    var loading = window.top.window.getIndexBusyOverlay();
    $.ajaxSettings['contentType'] = "application/x-www-form-urlencoded; charset=utf-8";
    $.ajax({
        type: "POST",
        url: "/rdfundReasonType/insertRdfundReasonType.action",
        data: JSON.stringify(data),
        contentType: "application/json;charset=utf-8",
        dataType: "json",
        beforeSend:function(){
            if(loading) {
            	loading.settext("正在处理中，请稍后...");
            }
        },
        success: function (json) {
        	loading.remove();
            if (json.result=="success") {
                newForm.modal('hide');
                $('#refundReasonCode').val('');
                $('#refundReasonName').val('');
                $('#remark').val('');
                window.top.window.showScoMessage('ok', '添加成功');
                rdfundReasonTypeTable.draw();
            } else {
            	loading.remove();
                window.top.window.showModalAlert(json.msg);
            }
        }
    });
});

// 弹出修改退款原因类型对话框
function operationEdit(btnEdit) {
    var refundReasonId = $(btnEdit).attr("refundReasonId");
    $.ajax({
        type: "POST",
        url: "/rdfundReasonType/getRdfundReasonTypeInfo/" + refundReasonId + ".action",
        data: null,
        contentType: "application/json;charset=utf-8",
        dataType: "json",
        success: function (data) {
            if (data.result == "success") {
                $('#refundReasonId_m').val(refundReasonId);
                $('#refundReasonCode_m').val(data.data.refundReasonCode);
                $('#refundReasonName_m').val(data.data.refundReasonName);
                $('#remark_m').val(data.data.remark);
                initApprOptionComp4Modify(data.data);
                var editDialog = window.top.window.borrowCustomModalDialog($("#frmModifyRdfundReasonType"));
                editDialog.modal({show:true, backdrop:'static'});
            }
        }
    });

    $('#frmModifyRdfundReasonType').modal('show');
}

// 保存修改退款原因类型
$("#btnSave_m").click(function () {
    window.top.window.returnCustomModalDialog();

    if(!$("#editForm").valid()) {
        window.top.window.borrowCustomModalDialog($("#frmModifyRdfundReasonType"));
        return false;
    }

    var refundReasonId = $('#refundReasonId_m').val();
    var refundReasonCode = $('#refundReasonCode_m').val();
    var refundReasonName = $('#refundReasonName_m').val();
    var remark = $('#remark_m').val();
    var data = {
        "refundReasonId": refundReasonId,
        "refundReasonCode": refundReasonCode,
        "refundReasonName": refundReasonName,
        "remark": remark
        // --- 审核选项设置 --- 
        ,"isForceAppr":getIsForceAppr($("#frmModifyRdfundReasonType"))
        ,"apprRule":getRuleContent($("#frmModifyRdfundReasonType"))
        // --- 审核选项设置 --- 
    }

    var edit=window.top.window.borrowCustomModalDialog($("#frmModifyRdfundReasonType"));

    var loading = window.top.window.getIndexBusyOverlay();
    $.ajaxSettings['contentType'] = "application/x-www-form-urlencoded; charset=utf-8";

    $.ajax({
        type: "POST",
        url: "/rdfundReasonType/updateRdfundReasonType.action",
        data: JSON.stringify(data),
        contentType: "application/json;charset=utf-8",
        dataType: "json",
        beforeSend:function(){
            if(loading) {
            	loading.settext("正在处理中，请稍后...");
            }
        },
        success: function (json) {
            if (json.result == "true") {
            	loading.remove();
                edit.modal('hide');
                $('#refundReasonCode_m').val('');
                $('#refundReasonName_m').val('');
                $('#remark_m').val('');
                window.top.window.showScoMessage('ok', '保存成功');
                rdfundReasonTypeTable.draw();
            } else {
            	loading.remove();
                window.top.window.showModalAlert(json.msg);
            }
        }
    });
});

// 删除退款原因类型
function operationDelete(btnDelete) {
    var refundReasonId = $(btnDelete).attr("refundReasonId");
    $('#refund_reason_id_delete').val(refundReasonId);
    window.top.window.showModalConfirm( "是否确认删除？", doDelete);
}

// 删除退款原因类型
function doDelete() {
    var refundReasonId = $('#refund_reason_id_delete').val();
    var loading = window.top.window.getIndexBusyOverlay();
    $.ajax({
        type: "POST",
        url: "/rdfundReasonType/deleteRdfundReasonType/" + refundReasonId + ".action",
        data: null,
        contentType: "application/json;charset=utf-8",
        dataType: "json",
        beforeSend:function(){
            if(loading) {
            	loading.settext("正在处理中，请稍后...");
            }
        },
        success: function (json) {
            if (json.success) {
            	loading.remove();
                window.top.window.showScoMessage('ok', '删除成功');
                rdfundReasonTypeTable.draw();
            } else {
            	loading.remove();
                window.top.window.showModalAlert(json.msg);
            }
        }
    });
}
$('#frmSelPlatform').on('shown.bs.modal', function (e) {
	  //表头重新绘制
	rdfundReasonRelationTable.columns.adjust().draw();;
	})

// 弹出平台退款原因list关联对话框
var rdfundReasonRelationFlg = false;
function operationSelect(btnSel) {
    if (rdfundReasonRelationFlg) {
        rdfundReasonRelationTable.destroy();
    }
    
    $('#refund_reason_id').val($(btnSel).attr("refundReasonId"));
    
    rdfundReasonRelationTable = $('#tblRdfundReasonRelation').DataTable({
        "paging": false,
        "processing": true,
        "serverSide": true,
        "dom": '<"bottom"rtflp>', 
        "searching": false,
        "scrollX" : "100%",
        "fixedHeader": true,
//	    "scrollXInner" : "110%",
        "deferRender": true,
        "ajax": {
            "url": "/rdfundReasonType/getRdfundReasonRelationList.action",
            "dataFilter": function(data) {
                var array = jQuery.parseJSON(data);
                return JSON.stringify({
                    data: array,
                    recordsTotal: array.length,
                    recordsFiltered: array.length
                });
            },
            "data": function ( d ) {
                d.refundReasonId = $('#refund_reason_id').val();
            }
        },
        "fnDrawCallback": function (oSettings) {
            window.top.window.$("#thRdfundReasonRelation").removeClass("sorting_asc");
        },
        "tableTools": {
            "sRowSelect": "bootstrap"
        },
        "columns": [
            {"data": "ecRefundReason", "searchable": false, "orderable": false},
            {"data": "platform", 
             "render": function ( data, type, row, meta ) {
                 if (row.platform == "tb") {
                     return "淘宝";
                 }else if(row.platform == "xvp"){
                     return "小V铺";
                 }else{
                     return "其它";
                 }
             },
             "searchable": false, "orderable": false},
            {"data": "goodsStatus", 
             "render": function ( data, type, row, meta ) {
                 if (row.goodsStatus == "received") {
                     return "已收到货";
                 } else {
                     return "未收到货";
                 }
             },
             "searchable": false, "orderable": false},
            {"data": "goodsReturn", 
             "render": function ( data, type, row, meta ) {
                 if (row.goodsReturn == "y") {
                     return "退货";
                 } else {
                     return "不退货";
                 }
             },
             "searchable": false, "orderable": false},
             {"mRender": function(data, type, row) {
                     return '<button data-relation-id="' + row.relationId + '" type="button" class="clickClass btn btn-danger btn-xs"><i class="fa fa-trash-o"></i>&nbsp;删除</button>';
               },
               "searchable": false, "orderable": false}
        ]
    });

    rdfundReasonRelationFlg = true;
    var selDialog = window.top.window.borrowCustomModalDialog($("#frmSelPlatform"));
    selDialog.modal({show:true, backdrop:'static'});
    $('#frmSelPlatform').modal('show');
}

// 删除平台退款原因关联
$('#tblRdfundReasonRelation').on("click", ".clickClass", function() {
    var relationId = $(this).data("relation-id");
    $('#relation_id_delete').val(relationId);
    window.top.window.showModalConfirm( "是否确认删除？", doRelationDelete);
});

// 删除平台退款原因关联
function doRelationDelete() {
    var relationId = $('#relation_id_delete').val();

    $.ajax({
        type: "POST",
        url: "/rdfundReasonType/deleteRdfundReasonRelation/" + relationId + ".action",
        data: null,
        contentType: "application/json;charset=utf-8",
        dataType: "json",
        success: function (json) {
            if (json.success) {
                window.top.window.showScoMessage('ok', '删除成功');
                rdfundReasonRelationTable.draw();
            } else {
                window.top.window.showModalAlert(json.msg);
            }
        }
    });
}

// 弹出平台退款原因list选择对话框
var ecRefundReasonFlg = false;
$("#btnSelPlatform").click(function () {
    if (ecRefundReasonFlg) {
        ecRefundReasonTable.destroy();
    }
    
    ecRefundReasonTable = $('#tblEcRefundReason').DataTable({
        "paging": false,
        "processing": true,
        "serverSide": true,
        "dom": '<"bottom"rtflp>', 
        "searching": false,
        "deferRender": true,
        "ajax": {
            "url": "/rdfundReasonType/getEcRefundReasonList.action",
            "dataFilter": function(data) {
                var array = jQuery.parseJSON(data);
                return JSON.stringify({
                    data: array,
                    recordsTotal: array.length,
                    recordsFiltered: array.length
                });
            },
            "data": function ( d ) {
            	var platform;
            	if ($('#platform').val() == null) {
            		platform = window.top.window.$('#platform').val();
            	} else {
            		platform = $('#platform').val();
            	}
                d.platform = platform;
            }
        },
        "fnDrawCallback": function (oSettings) {
            window.top.window.$("#thEcRefundReason").removeClass("sorting_asc");
        },
        "tableTools": {
            "sRowSelect": "bootstrap"
        },
        "columns": [
            {"data": "ecRefundReasonId",
             "render": function ( data, type, row, meta ) {
                           return '<input type="checkbox" value="' + row.ecRefundReasonId + '" />';
                       },
             "searchable": false, "orderable": false},
            {"data": "ecRefundReason", "searchable": false, "orderable": false}
        ]
    });
    
    ecRefundReasonFlg = true;
        
    window.top.window.returnCustomModalDialog();
    
    var selDialog = window.top.window.borrowCustomModalDialog($("#frmEditPlatform"));
    selDialog.modal({show:true, backdrop:'static'});
    $('#frmEditPlatform').modal('show');
});

// 平台来源改变时
$("#platform").change(function () {
	ecRefundReasonTable.draw();
});

// 保存平台退款原因关联
$("#btnSave_s").click(function () {
    var refundReasonArray = new Array();
    window.top.window.$("#tblEcRefundReason tbody input[type='checkbox']:checked").each(function(k,v){
        refundReasonArray.push(this.value + "|" + this.parentNode.nextSibling.innerText);
    });
    if(refundReasonArray.length==0){           
        return window.top.window.showModalAlert("请选中一条数据");
    }
    
    if(!window.top.window.$('#goodsStatusReceived').is(':checked') && !window.top.window.$('#goodsStatusUnreceived').is(':checked')) {
        return window.top.window.showModalAlert("请选择货物状态");
    }
    if(!window.top.window.$('#goodsReturnY').is(':checked') && !window.top.window.$('#goodsReturnN').is(':checked')) {
        return window.top.window.showModalAlert("请选择买家是否退货");
    }
    
    var loading = window.top.window.getIndexBusyOverlay();
    $.ajax({
        url : "/rdfundReasonType/saveRefundReasonRelation.action",
        type : "post",
        traditional:true,
        data : {
            refundReasonArray : refundReasonArray,
            refundReasonId : $('#refund_reason_id').val(),
            goodsStatusReceived : window.top.window.$('#goodsStatusReceived').is(':checked'),
            goodsStatusUnreceived : window.top.window.$('#goodsStatusUnreceived').is(':checked'),
            goodsReturnY : window.top.window.$('#goodsReturnY').is(':checked'),
            goodsReturnN : window.top.window.$('#goodsReturnN').is(':checked')
        },
        beforeSend:function(){
            if(loading) {
            	loading.settext("正在处理中，请稍后...");
            }
        },
        success : function(data) {
            if (data.result == "success") {
            	loading.remove();
                window.top.window.$('#goodsStatusReceived').attr("checked", false);
                window.top.window.$('#goodsStatusUnreceived').attr("checked", false);
                window.top.window.$('#goodsReturnY').attr("checked", false);
                window.top.window.$('#goodsReturnN').attr("checked", false);
                
                window.top.window.returnCustomModalDialog();
                $('#frmEditPlatform').modal('hide');
                rdfundReasonRelationTable.draw();
            } else { 
                var errMsg = data.msg;
                if(errMsg.length>8 && errMsg.substring(0,8)=="chcekErr") {
                    window.top.window.showModalAlert(errMsg.substring(9));
                } else {
                    window.top.window.showModalAlert("系统错误");
                }
            }
        },
        error : function(XMLHttpRequest, textStatus) {
        	loading.remove();
            if (XMLHttpRequest.status == 500) {
                var result = eval("(" + XMLHttpRequest.responseText + ")");
                window.top.window.showModalAlert(result.errorObject.errorText);
            }
        }
    });
});


// ------ 审核规则设置 ------
var getRuleContent = function(context){
    if(!context){
        context = window;
    }
    var returnValue = {
        cRS : {enable:""},
        rRS : {enable:"",hPR:"",hSG:""},
        rE : {enable:"",rUM:"",rB:""}
    };
    /*
     * 设置订单包含退款商品:
     * 如果选项选中，则启用校验；如果不选中，则不启用校验
     */ 
    if($("#chkContainRefundSku",context).is(":checked")){
        returnValue.cRS.enable = "y";
    }else{
        returnValue.cRS.enable = "n";
    }
    
    /*
     * 设置退货异常：
     * 如果退货异常启用，则必须启用“未创建退货单、退货单未完成、退货单已完成且退入数与退货数不符（商品品类或数量不符）”
     * “退货单已完成且退入数与退货数相符，但有破损（商品品类和数量都相符）”可以选择性启用
     */ 
    if($("#chkReturnException",context).is(":checked")){
        returnValue.rE.enable = "y";
        returnValue.rE.rUM = "y";
        
        if($("#returnBroken",context).is(":checked")){
            returnValue.rE.rB = "y";
        }else{
            returnValue.rE.rB = "n";
        }
        
    }else{
        returnValue.rE.enable = "n";
        returnValue.rE.rUM = "n";
        returnValue.rE.rB = "n";
    }
    
    /*
     * 设置关联单据状态：
     * 如果启用，则“有进行中的单据（未系统发货前出库，未完成的补发单）”和“订单出库单已发货”择1启用。
     */ 
    if($("#chkRefReciptState",context).is(":checked")){
        returnValue.rRS.enable = "y";
        if($("#hasProcessingRecipt",context).is(":checked")){
            returnValue.rRS.hPR = "y";
            returnValue.rRS.hSG = "n";
        }else{
            returnValue.rRS.hPR = "n";
            returnValue.rRS.hSG = "y";
        }
    }else{
        returnValue.rRS.enable = "n";
        returnValue.rRS.hPR = "n";
        returnValue.rRS.hSG = "n";
    }
    return JSON.stringify(returnValue);
}

var getIsForceAppr = function(context){
    var returnValue = "n";
    if(!context){
        context = window;
    }
    if($("#chkForceAppr",context).is(":checked")){
        returnValue = "y"
    }
    return returnValue;
}
// ------ 审核规则设置 ------
